package ooboo;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.swing.ImageIcon;

public class Assets {
	public static final Font USER_FONT = new Font("SansSerif",Font.BOLD,12);
	public static final Font TEXT_FONT = new Font("SansSerif",Font.PLAIN,12);
	public static final Font REPLY_FONT = new Font("SansSerif",Font.PLAIN,11);
	public static final Font DATE_FONT = new Font("SansSerif",Font.ITALIC,10);
	
	private static String OS = null;
	private static File appDir = null;
	private static boolean first = !new File(getAppDataFolder().getAbsolutePath() + 
			File.separator + "storage").exists();
	
	public static String getOS() {
		if(OS == null)
			OS = System.getProperty("os.name");
		return OS;
	}
	
	public static boolean isMac() {
		if (getOS().startsWith("Mac OS"))
			return true;
		return false;
	}
	
	public static File getAppDataFolder () {
		if(appDir == null)
		{
			getOS();
			if (OS.startsWith("Windows")) {
				appDir = new File (System.getenv("APPDATA") + File.separator + "ooboo");
			} else if (OS.startsWith("Mac OS")) {
				appDir = new File (System.getProperty("user.home") + File.separator + "Library" + 
						 File.separator + "Application Support" + File.separator + 
						"ooboo");
			} else if (OS.startsWith("Linux")) {
				appDir = new File (System.getProperty("user.home") + File.separator + ".ooboo");
			}
		}
		return appDir;
	}
	
	public static boolean isFirstRun()
	{
		return first;
	}
	
	public static void openUrl (String url) throws Exception{
		
		System.out.println(url);
		
		if (!url.startsWith("http://") && !url.startsWith("mailto:")) {
			url = "http://" + url;
		}
		
		Runtime runtime=Runtime.getRuntime();
		if (getOS().startsWith("Windows")) {
			String cmd = "rundll32 url.dll,FileProtocolHandler "+ url;
			runtime.exec(cmd);
		} else if (getOS().startsWith("Mac OS")){
			Class<?> fileMgrClass = Class.forName("com.apple.eio.FileManager");
			Method openURL = fileMgrClass.getDeclaredMethod("openURL", new Class[] {String.class});
			openURL.invoke(null, new Object[] {url});
		} else {
			String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
			String browser = null;
			for (int count = 0; count < browsers.length && browser == null; count++) {
				if (runtime.exec(new String[] {"which", browsers[count]}).waitFor() == 0) {
					browser = browsers[count];
				}
			}
			if (browser == null) {
				throw new Exception("Could not find web browser. Please open your browser and go to: " + url + " manually");
			} else {
				runtime.exec(new String[] {browser, url});
			}
		}
	}
	
	public static String getShortURL (String urlToShorten) throws IOException {
		URL url = new URL("http://api.bit.ly/shorten?version=2.0.1&longUrl=" + urlToShorten + "&login=ooboo&apiKey=R_998504c3d1da9763890c50cc6b99dfde");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		if (conn.getResponseCode() != 200) {
			throw new IOException(conn.getResponseMessage());
		}

		BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
		String line = rd.readLine().trim();
		while (!(line.startsWith("\"shortUrl\": ")) && line != null) {
			line = rd.readLine().trim();
		}
		rd.close();
		conn.disconnect();

		return line.subSequence(13, line.length()-2).toString();

	}
	
	public static String getLongURL (String shortURL) throws IOException {
		URL url = new URL("http://api.bit.ly/expand?version=2.0.1&shortUrl=" +shortURL + "&login=ooboo&apiKey=R_998504c3d1da9763890c50cc6b99dfde");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		if (conn.getResponseCode() != 200) {
			throw new IOException(conn.getResponseMessage());
		}

		BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
		String line = rd.readLine().trim();
		while (!(line.startsWith("\"longUrl\": ")) && line != null) {
			//System.out.println(line);
			line = rd.readLine().trim();
		}
		rd.close();
		conn.disconnect();

		return line.subSequence(12, line.length()-2).toString();

	}
	
	public static BufferedImage toBufferedImage (Image img) {
        img = new ImageIcon(img).getImage();
    
        BufferedImage bufferedImage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.BITMASK;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bufferedImage = gc.createCompatibleImage(img.getWidth(null), img.getHeight(null), transparency);
        } catch (HeadlessException e) {}
    
        if (bufferedImage == null) {
            int type = BufferedImage.TYPE_INT_ARGB;
            bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null), type);
        }

        Graphics g = bufferedImage.createGraphics();
    
        g.drawImage(img, 0, 0, null);
        g.dispose();
    
        return bufferedImage;
    }
	
}
